document.addEventListener('DOMContentLoaded', function() {
  // 下载相关元素
  const downloadUrl = document.getElementById('downloadUrl');
  const downloadBtn = document.getElementById('downloadBtn');
  const progressContainer = document.getElementById('progressContainer');
  const progressBar = document.getElementById('progressBar');
  const status = document.getElementById('status');

  // 图片相关元素
  const imageGrid = document.querySelector('.image-grid');
  const noImagesMessage = document.querySelector('.no-images');
  const downloadSelectedBtn = document.querySelector('.download-selected');
  const selectedCountSpan = document.querySelector('.selected-count');

  // 标签相关元素
  const navTabs = document.querySelectorAll('.nav-tab');
  const tabPanels = document.querySelectorAll('.tab-panel');

  // 主题管理
  const themeManager = {
    // 获取当前主题
    getCurrentTheme() {
      return localStorage.getItem('theme') || 'light';
    },

    // 设置主题
    setTheme(theme) {
      localStorage.setItem('theme', theme);
      document.documentElement.setAttribute('data-theme', theme);
      this.updateThemeButtons(theme);
    },

    // 更新主题按钮状态
    updateThemeButtons(currentTheme) {
      document.querySelectorAll('.theme-option').forEach(button => {
        button.classList.toggle('active', button.dataset.theme === currentTheme);
      });
    },

    // 初始化主题
    init() {
      // 设置初始主题
      const currentTheme = this.getCurrentTheme();
      this.setTheme(currentTheme);

      // 添加主题切换事件监听
      document.querySelectorAll('.theme-option').forEach(button => {
        button.addEventListener('click', () => {
          const theme = button.dataset.theme;
          this.setTheme(theme);
        });
      });

      // 监听系统主题变化
      if (window.matchMedia) {
        window.matchMedia('(prefers-color-scheme: dark)').addListener(e => {
          if (this.getCurrentTheme() === 'auto') {
            this.setTheme(e.matches ? 'dark' : 'light');
          }
        });
      }
    }
  };

  // 标签切换功能
  navTabs.forEach(tab => {
    tab.addEventListener('click', () => {
      // 移除所有标签的active类
      navTabs.forEach(t => t.classList.remove('active'));
      // 隐藏所有面板
      tabPanels.forEach(panel => panel.style.display = 'none');
      
      // 激活当前标签
      tab.classList.add('active');
      // 显示对应面板
      const tabName = tab.getAttribute('data-tab');
      document.getElementById(tabName + 'Tab').style.display = 'block';

      // 如果切换到图片标签，请求图片
      if (tabName === 'images') {
        requestImages();
      }
    });
  });

  // 请求当前页面的图片
  function requestImages() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {type: 'getImages'})
          .then(response => {
            if (response && response.images) {
              updateImageGrid(response.images);
            }
          })
          .catch(error => {
            console.log('Failed to get images:', error);
            // 显示错误信息给用户
            imageGrid.innerHTML = '<div class="error-message">无法获取图片，请刷新页面后重试。</div>';
          });
      }
    });
  }

  // 更新图片网格
  function updateImageGrid(images) {
    const imageGrid = document.querySelector('.image-grid');
    const downloadSelectedBtn = document.querySelector('.download-selected');
    const selectedCountSpan = document.querySelector('.selected-count');
    
    if (!images || images.length === 0) {
      imageGrid.innerHTML = `
        <div class="error-message">
          <div style="font-size: 48px; text-align: center; margin-bottom: 16px;">🖼️</div>
          <div style="text-align: center;">当前页面未发现图片</div>
        </div>
      `;
      downloadSelectedBtn.style.display = 'none';
      return;
    }

    imageGrid.innerHTML = images.map((image, index) => `
      <div class="image-item" data-index="${index}" data-src="${image.src}">
        <img src="${image.src}" alt="${image.alt}" loading="lazy">
        <div class="image-info">
          <div>${image.width} x ${image.height}</div>
        </div>
      </div>
    `).join('');

    // 图片选择逻辑
    const selectedImages = new Set();
    const imageItems = imageGrid.querySelectorAll('.image-item');

    imageItems.forEach(item => {
      item.addEventListener('click', () => {
        item.classList.toggle('selected');
        const src = item.dataset.src;
        
        if (selectedImages.has(src)) {
          selectedImages.delete(src);
        } else {
          selectedImages.add(src);
        }

        // 更新下载按钮状态和选中计数
        const selectedCount = selectedImages.size;
        downloadSelectedBtn.style.display = selectedCount > 0 ? 'flex' : 'none';
        selectedCountSpan.textContent = selectedCount > 0 ? `(${selectedCount})` : '';
        
        // 添加选中动画
        if (item.classList.contains('selected')) {
          item.style.animation = 'scaleUp 0.3s ease';
        } else {
          item.style.animation = 'scaleDown 0.3s ease';
        }
      });
    });

    // 批量下载选中的图片
    downloadSelectedBtn.addEventListener('click', () => {
      const imagesToDownload = Array.from(selectedImages);
      if (imagesToDownload.length === 0) return;

      // 显示下载进度
      status.textContent = `正在下载 ${imagesToDownload.length} 张图片...`;
      progressContainer.style.display = 'block';
      
      // 批量下载
      let completed = 0;
      imagesToDownload.forEach(src => {
        chrome.runtime.sendMessage({
          type: 'download',
          url: src,
          filename: `image_${Date.now()}_${Math.random().toString(36).substr(2, 5)}.jpg`
        })
        .then(() => {
          completed++;
          const progress = (completed / imagesToDownload.length) * 100;
          progressBar.style.width = `${progress}%`;
          
          if (completed === imagesToDownload.length) {
            status.textContent = '所有图片下载完成！';
            setTimeout(() => {
              progressContainer.style.display = 'none';
              status.textContent = '';
            }, 2000);
          }
        })
        .catch(error => {
          console.error('Download failed:', error);
          status.textContent = '部分图片下载失败，请重试';
        });
      });

      // 清除选中状态
      imageItems.forEach(item => item.classList.remove('selected'));
      selectedImages.clear();
      downloadSelectedBtn.style.display = 'none';
      selectedCountSpan.textContent = '';
    });
  }

  // 添加选中动画样式
  const style = document.createElement('style');
  style.textContent = `
    @keyframes scaleUp {
      from { transform: scale(0.95); opacity: 0.8; }
      to { transform: scale(1); opacity: 1; }
    }
    @keyframes scaleDown {
      from { transform: scale(1.05); opacity: 1; }
      to { transform: scale(1); opacity: 0.8; }
    }
  `;
  document.head.appendChild(style);

  // 单个URL下载功能
  let currentDownloadId = null;

  downloadBtn.addEventListener('click', function() {
    const url = downloadUrl.value.trim();
    
    if (!url) {
      status.textContent = 'Please enter a valid URL';
      return;
    }

    if (!isValidUrl(url)) {
      status.textContent = '请输入有效的URL';
      return;
    }

    startDownload(url);
  });

  function isValidUrl(string) {
    try {
      new URL(string);
      return true;
    } catch (_) {
      return false;
    }
  }

  function startDownload(url) {
    if (!isValidUrl(url)) {
      status.textContent = '请输入有效的URL';
      return;
    }

    progressContainer.style.display = 'block';
    status.textContent = '开始下载...';

    // 发送下载请求到background script
    chrome.runtime.sendMessage({
      type: 'download',
      url: url,
      filename: getFilenameFromUrl(url),
      saveAs: false
    })
    .then(response => {
      if (response.success) {
        monitorDownload(response.downloadId);
      } else {
        handleError(response.error || '下载失败');
      }
    })
    .catch(error => {
      handleError(error.message || '下载请求失败');
    });
  }

  function getFilenameFromUrl(url) {
    try {
      const urlObj = new URL(url);
      const pathname = urlObj.pathname;
      const filename = pathname.substring(pathname.lastIndexOf('/') + 1);
      return filename || 'downloaded_file';
    } catch (e) {
      return 'downloaded_file';
    }
  }

  function monitorDownload(downloadId) {
    chrome.downloads.search({id: downloadId}, function(results) {
      if (results && results[0]) {
        const download = results[0];
        
        if (download.error) {
          handleError(download.error);
          return;
        }

        const progress = (download.bytesReceived / download.totalBytes) * 100;
        updateProgress(progress);

        if (download.state === 'complete') {
          downloadComplete();
        } else if (download.state === 'in_progress') {
          setTimeout(() => monitorDownload(downloadId), 100);
        }
      }
    });
  }

  function updateProgress(percent) {
    const progress = Math.round(percent);
    progressBar.style.width = `${progress}%`;
    status.textContent = `Downloading: ${progress}%`;
  }

  function downloadComplete() {
    status.textContent = 'Download completed!';
    downloadBtn.disabled = false;
    setTimeout(() => {
      progressContainer.style.display = 'none';
      status.textContent = '';
      downloadUrl.value = '';
    }, 3000);
  }

  function handleError(error) {
    status.textContent = `Error: ${error.message || 'Download failed'}`;
    downloadBtn.disabled = false;
    progressContainer.style.display = 'none';
  }

  // 初始化时请求图片
  requestImages();

  // 初始化主题管理器
  themeManager.init();
});
